<template>
  <el-drawer v-model="drawer" :before-close="handleClose" size="70%" modal-class="pay-drawer">
    <template #header>
      <title-view title="添加发包" />
    </template>
    <el-select v-model="type" placeholder="请选择" style="width: 200px" clearable @change="handleChange" @clear="handleChange">
      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <el-table
      ref="myTable"
      class="custom-table"
      :data="tableData"
      row-key="spaceIdTree"
      :height="tableHeight"
      :tree-props="treeProps"
      :expand-row-keys="expandRowKeys"
      :row-class-name="tableRowClassName"
      @expand-change="handleExpandChange"
      @selection-change="selectionChange"
      @select-all="handleSelectAll"
      @select="handleSelect"
      style="width: 100%; margin-top: 20px"
      :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="date" label="名称" width="150" show-overflow-tooltip>
        <template #header>
          <div style="display: flex; align-items: center">
            <div>名称</div>
            <div style="margin-top: 8px; margin-left: 6px">
              <img
                v-if="isExpansion"
                @click="toggleExpandAll"
                style="width: 20px; cursor: pointer"
                src="@/assets/images/image/sq.png"
                alt=""
              />
              <img
                v-else
                @click="toggleExpandAll"
                style="width: 20px; cursor: pointer"
                src="@/assets/images/image/zk.png"
                alt=""
              />
            </div>
          </div>
        </template>
        <template #default="{ row }">
          {{ row.quotaInfoVOList ? row.spaceName : row.quotaName }}
        </template>
      </el-table-column>
      <el-table-column prop="address" label="明细" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.mainSubcontractMoney">主材：￥{{ row.mainSubcontractMoney }}/</span>
          <span v-if="row.auxiliarySubcontractMoney">辅材：¥{{ row.auxiliarySubcontractMoney }}/</span>
          <span v-if="row.workerSubcontractMoney">人工：¥{{ row.workerSubcontractMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" show-overflow-tooltip width="60">
        <template #default="{ row }">
          {{ unitData.find(item => item.dictValue == row.unit)?.dictLabel }}
        </template>
      </el-table-column>
      <el-table-column prop="actualProjectVal" label="实际施工量" show-overflow-tooltip />
      <el-table-column prop="contracteesNum" label="发包量" width="100" />
      <el-table-column prop="subcontractTotalMoney" label="发包单价" width="100" />
      <el-table-column prop="subcontractTotalMoneyCnt" label="发包价(发包量*单价)" show-overflow-tooltip width="160" />
      <el-table-column prop="bindNames" label="品牌" show-overflow-tooltip />
      <el-table-column prop="modelNames" label="型号" show-overflow-tooltip />
    </el-table>
    <template #footer>
      <div style="display: flex; justify-content: space-between; align-items: center">
        <div>
          <span>共选择{{ length }}项</span>
        </div>
        <div>
          <el-button @click="handleClose" color="#F2F3F5">取消</el-button>
          <el-button type="primary" plain @click="confirmClick">保存</el-button>
        </div>
      </div>
    </template>
  </el-drawer>
</template>
<script setup>
import { computed, nextTick, ref } from "vue";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash";
import { getCache } from "@/utils/cache";
import { getTemplate, saveContractees } from "@/apis/contracting";
import { selectDictDataByType } from "@/apis/dict/dict";

const unitData = ref([]);
const tableHeight = ref(600);
const treeProps = ref({
  checkStrictly: false,
  children: "quotaInfoVOList"
});
const tableData = ref([]);
const options = ref([
  {
    value: 1,
    label: "主材"
  },
  {
    value: 2,
    label: "辅材"
  },
  {
    value: 3,
    label: "人工"
  }
]);
const expandRowKeys = ref([]);
const myTable = ref();
const emit = defineEmits(["handleActive"]);
const drawer = ref(false);
const isExpansion = ref(true);
const type = ref(null);
const contracteesId = ref("");
const selectedReformIds = ref([]);
const length = computed(() => {
  let num = 0;
  selectedReformIds.value.map(item => {
    if (!item.quotaInfoVOList) {
      num += 1;
    }
  });
  return num;
});
// 只能选择已判责、已核实任务进行核实
const selectionChange = newSelection => {
  selectedReformIds.value = newSelection;
  toggleRowSelection(setData().noChildrenIds);
};
const getUnit = async () => {
  const { data } = await selectDictDataByType("shop_unit");
  unitData.value = data || [];
};

const setData = () => {
  let childrenData = [];
  const result = { contentIds: [], noChildrenIds: [] };
  let tableDataList = cloneDeep(tableData.value);
  selectedReformIds.value.map(item => {
    if (!item.quotaInfoVOList) {
      childrenData.push(item);
      result.contentIds.push(item.spaceIdTree);
    }
  });
  tableDataList.forEach(item => {
    item.quotaInfoVOList = [];
    childrenData.map(items => {
      if (items.parentId === item.spaceIdTree) {
        item.quotaInfoVOList.push(items);
      }
    });
    if (!item.quotaInfoVOList.length > 0) {
      result.noChildrenIds.push(item);
    }
  });
  return result;
};
const toggleRowSelection = noChildrenIds => {
  tableData.value.forEach(item => {
    noChildrenIds.map(items => {
      if (item.spaceIdTree === items.spaceIdTree) {
        myTable.value?.toggleRowSelection(item, false);
      }
    });
  });
};
// 勾选或者取消勾选
const handleSelect = (selection, row) => {
  const selectedIds = selection.filter(item => !item.quotaInfoVOList).map(item => item.spaceIdTree);
  const isRowSelected = selection.some(item => item.spaceIdTree === row.spaceIdTree);
  if (isRowSelected) {
    tableData.value.forEach(item => {
      const isParent = row.parentId === item.spaceIdTree;
      if (isParent) {
        myTable.value.toggleRowSelection(item, true);
      }
      item.quotaInfoVOList.forEach(items => {
        if (!selectedIds.includes(items.spaceIdTree)) {
          myTable.value.toggleRowSelection(items, false);
        }
      });
    });
  }
};
// 全选/反选
const handleSelectAll = selection => {
  selectedReformIds.value = selection;
};
// 清空选中
const handelBatchClearing = () => {
  myTable.value?.clearSelection();
  selectedReformIds.value = [];
};
// 关闭
const handleClose = () => {
  drawer.value = false;
};
// 提交
const confirmClick = async () => {
  if (selectedReformIds.value.length > 0) {
    await saveContractees({ contentIds: setData().contentIds, code: getCache("randomCode") });
    myTable.value?.clearSelection();
    drawer.value = false;
    emit("handleActive", setData().contentIds);
  } else {
    ElMessage.error("请选择发包项添加！");
  }
};
const openDrawer = async id => {
  expandRowKeys.value = [];
  contracteesId.value = id;
  await getTemplateList();
  drawer.value = true;
  isExpansion.value = true;
  await getUnit();
  handelBatchClearing();
  setHeight();
};
const handleChange = () => {
  getTemplateList();
};
const getTemplateList = async () => {
  const { data } = await getTemplate({
    contracteesId: contracteesId.value,
    type: type.value,
    code: getCache("randomCode")
  });
  let ids = [];
  data.map(item => {
    ids.push(item.spaceId);
  });
  expandRowKeys.value = ids;
  tableData.value = data || [];
};
const toggleExpandAll = () => {
  isExpansion.value = !isExpansion.value;
  if (isExpansion.value) {
    toggleRowExpansionAll(tableData.value, isExpansion);
  } else {
    expandRowKeys.value = [];
  }
};
const toggleRowExpansionAll = (data, isExpansion) => {
  data.forEach(item => {
    myTable.value?.toggleRowExpansion(item, isExpansion);
    if (item.quotaInfoVOList !== undefined && item.quotaInfoVOList !== null) {
      toggleRowExpansionAll(item.quotaInfoVOList, isExpansion);
    }
  });
};
const tableRowClassName = ({ row }) => {
  if (expandRowKeys.value.includes(row.spaceIdTree)) {
    return "active-row";
  }
  return "init-row";
};
const handleExpandChange = (row, expanded) => {
  if (expanded) {
    expandRowKeys.value.push(row.spaceIdTree);
  } else {
    const index = expandRowKeys.value.indexOf(row.spaceIdTree);
    if (index !== -1) {
      expandRowKeys.value.splice(index, 1);
    }
  }
  isExpansion.value = expandRowKeys.value.length > 0;
};
const setHeight = () => {
  nextTick(() => {
    tableHeight.value = document.documentElement.clientHeight - 220;
    console.log(isExpansion.value, 999);
  });
};
defineExpose({ openDrawer });
</script>
<style scoped lang="scss">
.pay-drawer {
  :deep(.el-drawer) {
    min-width: 525px;
    background: #ffffff;
    box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.04) !important;
    border-radius: 20px 0px 0px 20px !important;
  }
}

/* 自定义树状表格图标 */
/* 有子节点 且未展开 */
.custom-table :deep(.el-table__expand-icon) {
  background: url("@/assets/images/image/zk1.png") no-repeat;
  width: 16px !important;
  height: 16px !important;
  font-size: 16px !important;
  background-size: 16px !important;

  .el-icon {
    display: flex;

    svg {
      width: 0 !important;
    }
  }
}

/* 有子节点 且已展开 */
.custom-table :deep(.el-table__expand-icon--expanded) {
  background: url("@/assets/images/image/sq1.png") no-repeat;
  width: 16px !important;
  height: 16px !important;
  font-size: 16px !important;
  background-size: 16px !important;
  transform: rotate(180deg); /* 展开时旋转 */
  .el-icon {
    display: flex;

    svg {
      width: 0 !important;
    }
  }
}

.custom-table :deep(.active-row) {
  background-color: #d9e8ff !important;
}

:deep(.el-select__wrapper) {
  background: #f2f3f5 !important;
}

.custom-table :deep(.init-row) {
  background-color: #f5f7fa !important;
}
</style>
